<template>
	<!-- 购买商品订单详情 -->
	<view class="privilege-order">
        <view v-if="is_address=='2'">
            <!-- 有地址 -->
            <view class="person-msg-address" v-if="hasAds" @click="toChooseAddress">
            	<view class="name-phone">
            		<text style="margin-right: 30upx;font-weight:550;">{{userDefaultAds.name}}</text>
            		<text>{{userDefaultAds.mobile}}</text>
            	</view>
            	<view class="address">
            		<view style="margin-right: 28upx;">
            			收货地址：<text>{{userDefaultAds.address}}</text>
            		</view>
            		<image :src="arrow_right" style="width: 14upx;height: 26upx;"></image>
            	</view>
            </view>
            <!-- 无地址 -->
            <view class="add-person-msg-address" v-if="!hasAds">
            	<view style="display: flex;justify-content: space-between;" @click="toChooseAddress">
            		<text>收货地址：</text>
            		<image :src="arrow_right" style="width: 14upx;height: 26upx;"></image>
            	</view>
            	<view class="add-adress" @click="toChooseAddress">
            		+请添加地址
            	</view>
            </view>
        </view>
		
		<view class="goods-msg">
			<view style="width: 304upx;height: 228upx;">
				<image :src="item.product.img_src" style="width: 100%;height: 100%;"></image>
			</view>
			<view class="goods-price">
				<view>{{item.product.title|privi_val}}</view>
				<view class="privilege-money-participation" style="display: flex;justify-content: space-between;">
					<view style="padding-top: 10upx;box-sizing: border-box;display:flex;align-items:center;">
						<image :src="lucky_Achievement" style="width: 32upx;height: 32upx;" v-if="item.product.achievement_value>0"></image>
						<text style="color: #FF3C00;font-size: 32upx;margin-right: 10upx;"><text v-if="item.product.achievement_value>0">{{item.product.achievement_value}}+</text>￥{{item.product.price}}</text>
						<text style="color: #cccccc;font-size: 24upx;text-decoration: line-through;line-height: 34upx;">￥{{item.product.original_price}}</text>
					</view>
				</view>
				<view class="count">
					<view @click="buyGoodsCount(false)">
						-
					</view>
					<view style="color: #333333;">
						{{buyCount}}
					</view>
					<view @click="buyGoodsCount(true)">
						+
					</view>
				</view>
			</view>
		</view>
		<view class="privilege-coupon" v-if="item.product.discounted_price>0">
			<view>
				特权优惠：会员自购
			</view>
			<view style="display: flex;justify-content: space-between;">
				<text class="color">-{{item.product.discounted_price}}</text>
				<text>x{{buyCount}}</text>
				<text class="color">-{{totalDisCountPrice}}</text>
			</view>
		</view>
		<view class="privilege-coupon" v-if="item.product.get_achievement_value>0">
			<view style="display: flex;align-items: center;">
				<image :src="lucky_Achievement" style="width: 48upx;height: 48upx;margin-right: 10upx;"></image>
				<text>赠送成就值：</text>
			</view>
			<view style="display: flex;justify-content: space-between;">
				<text class="color">+{{item.product.get_achievement_value}}</text>
				<text>x{{buyCount}}</text>
				<text class="color">+{{item.product.get_achievement_value*buyCount}}</text>
			</view>
		</view>
		<!-- 支付方式 -->
		<view class="pay-type">
			<view>
				<view style="width: 6upx;height: 32upx;background: #00A66A;border-radius: 3upx;margin-top: 8upx;"></view>
				<view style="margin-left: 14upx">
					支付方式
				</view>
			</view>
			<view>
				<radio-group @change="radioChange">
					<label class="we-chat" v-for="(one,index) in payType" :key='index' @click="tapRadio(index)">
						<view>
							<image :src="one.src" style="width: 56upx;height: 56upx;"></image>
							<text>{{one.name}}</text>
						</view>
						<radio :value="one.value" :checked="index === current" :disabled="(item.user_balance<totalOrderPrice&&index==1)||(index==0&&totalOrderPrice==0)?true:false" />
					</label>
				</radio-group>
			</view>
		</view>
		<!-- 留言备注 -->
		<view class="goods-remarks">
			<view>
				<view style="width: 6upx;height: 32upx;background: #00A66A;border-radius: 3upx;margin-top: 8upx;"></view>
				<view style="margin-left: 14upx">
					备注
				</view>
			</view>
			<view>
				<textarea v-model="note" placeholder="请填写你需要备注的信息" style="width: 100%;height: 100%;" />
				</view>
		</view>
		<view class="pay-price">
			<view style="display: flex;" class="pay-price-one">
				<view style="margin-right: 10upx;">
					合计：
				</view>
				<view class="privilege-money-participation" style="margin: 0;">
					<view style="display: flex;align-items: center;">
						<image :src="lucky_Achievement" style="width: 32upx;height: 32upx;" v-if="(item.product.achievement_value*buyCount)>0"></image>
						<text style="color: #FF3C00;font-size: 32upx;margin-right: 10upx;"><text v-if="(item.product.achievement_value*buyCount)>0">{{item.product.achievement_value*buyCount}}+</text>￥{{totalOrderPrice}}</text>
					</view>
				</view>
			</view>
			<view @click="payMoneyBeform" class="pay-price-two" v-if="totalOrderPrice>0||(item.product.achievement_value*buyCount)>0">
				立即支付
			</view>
			<view @click="payMoneyBeform" class="pay-price-two" v-else>
				立即下单
			</view>
		</view>
	</view>
</template>

<script>
	export default{
		data(){
			return {
				arrow_right: this.$imgUrl+'img/arrow_right.png',
				lucky_Achievement: this.$imgUrl+'img/riddle/lucky_Achievement.png',
				buyCount: 1,
				payType:[
					{name:'微信',value:'Wechat',src:this.$imgUrl+'img/privilege/pay-wechat.png'},
					{name:'余额',value:'remainingSum',src:this.$imgUrl+'img/privilege/remaining_sum.png'}
				],
				current: 0,
				token: this.$store.getters.getToken,
				userId: this.$store.getters.getUserId,
				userDefaultAds: {},
				hasAds: true,
                is_address:null,
				totalDisCountPrice: 0,
				totalOrderPrice: 0,
				// 活动id
				id: 0,
				// 备注
				note: '',
				// 提交订单数据
				item: {
					// 用户拥有的成就值
					achievement_value: 0,
					// 用户余额
					user_balance: 0,
					// 订单支付的价格
					order_price: 0,
					product: {
						img_src: '',
						title: '',
						price: 0,
						original_price: 0,
						achievement_value: 0,
						limited_number: 0,
						discounted_price: 0,
						get_achievement_value: 0,
						// 用户已经参与活动的次数
						frequency: 0,
						type: 1,//1不是实物，2是实物
					}
				},
				// 订单id
				order_id: 0,
				share_id: '',
				canPay: true,
				isIos:this.$isIos
			}
		},
		filters: {
			privi_val(value) {
				if (!value) return ''
				if (value.length > 28) {
					return value.slice(0, 28) + '...'
				}
				return value
			}
		},
		onShow() {
			this.getAddr()
		},
		onLoad(options) {
			this.id = options.id
			this.share_id = options.share_id
			this.item = JSON.parse(options.item) 
			console.log('item 88888888',this.item)
			this.item.order_price = this.item.order_price.toFixed(2)
			this.totalDisCountPrice = (this.buyCount*this.item.product.discounted_price).toFixed(2)
			this.totalOrderPrice = (this.item.order_price*this.buyCount).toFixed(2)
			if(this.totalOrderPrice==0){
				this.current=1
			}
            this.is_address = options.is_address
            console.log(this.is_address,'88888888888888888888888888888');
		},
		watch:{
			buyCount(newVal,oldVal) {
				if(newVal!=oldVal) {
					this.totalDisCountPrice = (this.buyCount*this.item.product.discounted_price).toFixed(2)
					this.totalOrderPrice = (this.item.order_price*this.buyCount).toFixed(2)
					if(this.totalOrderPrice==0){
						this.current=1
					}
				}
			}
		},
		methods:{
			getAddr(){
				let data ={
					token:this.token,
					userID:this.userId
				}
				this.$api.getAddrList(data).then(res => {
					if(res.status){
						this.hasAds = false
						var addrList = res.list
						var reg = /^(\d{3})\d{4}(\d{4})$/
						for(let i = 0;i < addrList.length; i++){
							if(addrList[i].isDefault==1) {
								this.userDefaultAds = addrList[i]
								this.hasAds = true
								break;
							}
						}
					}else {
						this.hasAds = false
					}
				}).catch(err => {
					console.log('用户地址',err)
				})
			},
			buyGoodsCount(flag){
				if(flag){
					if(this.item.product.limited_number-this.item.product.frequency>this.buyCount) {
						this.buyCount += 1
					}else {
						uni.showToast({
							title: '已达该活动最大限购数！',
							icon: 'none',
							duration: 2000
						})
					}
				}else{
					if(this.buyCount>1) {
						this.buyCount -= 1
					}
				}
			},
			radioChange: function(evt) {
				for (let i = 0; i < this.payType.length; i++) {
					if(this.payType[i].value === evt.target.value) {
						this.current = i;
						console.log('4444444444',typeof this.current)
						break;
					}
				}
			},
			tapRadio(index) {
				if(this.item.user_balance<this.totalOrderPrice&&index==1) {
					uni.showToast({
						title: '账户余额不足！',
						icon: 'none',
						duration: 2000
					})
				}else if(this.totalOrderPrice==0&&index==0) {
					uni.showToast({
						title: '不支持微信支付！',
						icon: 'none',
						duration: 2000
					})
				}
			},
			// 去选择地址
			toChooseAddress() {
				uni.navigateTo({
					url: '../../memberCenter/addressManage/addressManage'
				})
			},
			callPay(jsApiParameters) {
				if (typeof WeixinJSBridge == "undefined"){
					if( document.addEventListener ){
						document.addEventListener('WeixinJSBridgeReady', this.jsApiCall, false);
					}else if (document.attachEvent){
						document.attachEvent('WeixinJSBridgeReady', this.jsApiCall);
						document.attachEvent('onWeixinJSBridgeReady', this.jsApiCall);
					}
				}else{
					this.jsApiCall(jsApiParameters);
				}
			},
			jsApiCall(jsApiParameters)
			{ 
			  WeixinJSBridge.invoke(
				'getBrandWCPayRequest',jsApiParameters,
				function(res){
				  WeixinJSBridge.log(res.err_msg);
				  if (res.err_msg == "get_brand_wcpay_request:ok") {
					alert('支付成功')
					   //可以进行查看订单，等操作
				  } else {
						alert('支付失败！');
				  }
				  alert(res.err_code+res.err_desc+res.err_msg);
				}
			  );
			},
            payMoneyBeform(){
                console.log(this.is_address,'-----------------',this.hasAds);
                if(this.is_address == '2' && !this.hasAds){
                    uni.showToast({
                    	title: "请填写地址",
                    	duration: 1000,
                    	icon: "none",
                    	mask: true
                    })
                }else{
                    this.payMoney()
                }
            },
			// 立即支付
			payMoney() {
				if(this.item.achievement_value<this.item.product.achievement_value*this.buyCount) {
					uni.showToast({
						title: '账户成就值不足！',
						icon: 'none',
						duration: 2000
					})
					setTimeout(()=>{
						uni.navigateBack({})
					},1500)
				}else {
					if(this.canPay) {
						this.canPay=false
						setTimeout(()=>{
							this.canPay=true
						},2000)
						uni.showLoading({
							title: '下单中...',
						});
						// 发起支付
						let data = {
							token: this.token,
							id: this.id,
							address_id: this.userDefaultAds.id,
							pay_type: this.current+1,//支付类型1:微信支付2:余额支付
							num: this.buyCount,
							note: this.note,
							share_id: this.share_id,
							isNoNeedLoading: true
						}
						this.$api.submitOrder(data).then(res => {
							console.log('发起支付',res)
							if(res.status) {
								uni.hideLoading();
								this.order_id = res.order_id
								let self = this

								if(self.current+1==1) {//微信支付
									let payment = res.data.res
									//#ifdef H5
									payment = JSON.parse(payment);
									 this.callPay(payment)
									 uni.navigateTo({
									 	url: "../buySucceed/buySucceed?order_id=" + self.order_id+'&id='+self.id,
									 })
									//#endif
									// #ifdef MP-WEIXIN
									uni.requestPayment({
										provider: 'wxpay',
										timeStamp: payment.timeStamp.toString(),
										nonceStr: payment.nonceStr,
										package: payment.package,
										signType: payment.signType,
										paySign: payment.paySign,
										success: function(res) {
											uni.showToast({
												title: "支付成功",
												duration: 1000,
												icon: "none",
												mask: true
											})
											setTimeout(function() {
												uni.navigateTo({
													url: "../buySucceed/buySucceed?order_id=" + self.order_id+'&id='+self.id,
												})
											}, 1000)
										},
										fail: function(err) {
											console.log(JSON.stringify(err));
											uni.showToast({
												title: "支付失败",
												duration: 1000,
												icon: "none",
												mask: true
											})
											setTimeout(function() {
												uni.navigateBack({})
											}, 1000)
										}
									});
									// #endif
								}else {//余额支付
									setTimeout(function() {
										uni.navigateTo({
											url: "../buySucceed/buySucceed?order_id=" + self.order_id+'&id='+self.id,
										})
									}, 1000)
								}
							}else {
								uni.showToast({
									title: res.msg,
									icon: 'none',
									duration: 2000
								})
								setTimeout(()=>{
									uni.hideLoading();
								},1000)
							}
						}).catch(err => {
							uni.hideLoading();
							console.log('发起支付',err)
						})
					}else{
						uni.showToast({
							title: '请稍后...',
							icon: 'none',
							duration: 2000
						})
					}
				}
			}
		}
	}
</script>

<style>
	page{
		background: #F5F6F9;
	}
	.privilege-order{
		position: relative;
		width: 100%;
		background: #F5F6F9;
		padding-bottom: 126upx;
	}
	.person-msg-address{
		width: 100%;
		background: #fff;
		padding: 22upx 40upx 24upx 30upx;
		box-sizing: border-box;
	}
	.add-person-msg-address{
		width: 100%;
		height: 240upx;
		background: #fff;
		padding: 22upx 40upx 24upx 30upx;
		box-sizing: border-box;
	}
	.name-phone>text{
		display: inline-block;
		color: #333333;
	}
	.address{
		font-size: 28upx;
		color: #333333;
		display: flex;
		justify-content: space-between;
		margin-top: 8upx;
	}
	.add-adress{
		width: 430upx;
		height: 80upx;
		line-height: 80upx;
		box-sizing: border-box;
		border: 2upx solid #00A66A;
		border-radius: 40upx;
		text-align: center;
		color: #00A66A;
		font-size: 30upx;
		margin: 0 auto;
		margin-top: 66upx;
		font-weight: 580;
	}
	.goods-msg{
		width: 100%;
		height: 302upx;
		background: #FFFFFF;
		margin-top: 20upx;
		padding: 36upx 30upx 38upx 30upx;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
	}
	.goods-price{
		width: 366upx;
		position: relative;
	}
	.goods-price>view:first-child{
		font-size: 30upx;
		color: #333;
		font-weight: 800;
	}
	.privilege-money-participation{
		margin-top: 32upx;
		display: flex;
		align-items: center;
	}
	.privilege-money-participation>view:first-child text:nth-child(1){
		display: inline-block;
		height: 44upx;
		line-height: 44upx;
	}
	.count{
		width: 200upx;
		height: 44upx;
		line-height: 44upx;
		background: #F2F2F2;
		border: 1upx solid #DEDEDE;
		border-radius: 22upx;
		display: flex;
		text-align: center;
		color: #999999;
		position: absolute;
		bottom: 0;right: 0;
	}
	.count>view{
		width: 33%;
		line-height: 1.3;
	}
	.count>view:nth-child(2){
		border-left: 1upx solid #DEDEDE;
		border-right: 1upx solid #DEDEDE;
	}
	.privilege-coupon{
		width: 100%;
		height: 122upx;
		background: #FFFFFF;
		margin-top: 20upx;
		padding: 40upx 30upx;
		box-sizing: border-box;
		line-height: 42upx;
		display: flex;
		justify-content: space-between;
		font-size: 30upx;
	}
	.privilege-coupon>view:first-child{
		color: #666666;
	}
	.privilege-coupon>view:last-child{
		width: 360upx;
		color: #666666;
	}
	.privilege-coupon>view:last-child .color{
		color: #FF5C46;
	}
	.pay-type{
		width: 100%;
		height: 290upx;
		padding: 0 30upx;
		box-sizing: border-box;
		background: #FFFFFF;
		margin-top: 20upx;
	}
	.pay-type>view:last-child label{
		display: block;
		padding: 22upx 0;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
		color: #333333;
		font-size: 30upx;
	}
	.pay-type .we-chat{
		border-bottom: 1upx solid #DEDEDE;
	}
	.pay-type .we-chat image{
		vertical-align: middle;
	}
	.pay-type .we-chat text{
		vertical-align: middle;
		display: inline-block;
		margin-left: 20upx;
	}
	.goods-remarks{
		width: 100%;
		height: 332upx;
		padding: 0 30upx;
		box-sizing: border-box;
		background: #FFFFFF;
		margin-top: 20upx;
	}
	.pay-type>view:first-child{
		border-bottom: 1upx solid #DEDEDE;
	}
	.goods-remarks>view:first-child,.pay-type>view:first-child{
		padding: 22upx 0;
		box-sizing: border-box;
		font-size: 30upx;
		color: #333;
		line-height: 42upx;
		display: flex;
	}
	.goods-remarks>view:nth-child(2){
		width: 100%;
		height: 206upx;
		background: #F2F2F2;
		border-radius: 8upx;
		padding: 20upx;
		box-sizing: border-box;
	}
	.pay-price{
		position: fixed;
		bottom: 0;
		width: 100%;
		height: 100upx;
		line-height: 100upx;
		background: #FFFFFF;
		margin-top: 20upx;
		padding-left: 34upx;
		padding-right: 28upx;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
	}
	.pay-price .pay-price-one{
		line-height: 100upx;
	}
	.pay-price .pay-price-two{
		width: 262upx;
		height: 80upx;
		background: linear-gradient(#B3EA00,#00A66A);
		box-shadow: 0 4upx 8upx 0 rgba(0, 166, 106, 0.35);
		border-radius: 40upx;
		color: #FFFFFF;
		font-size: 30upx;
		text-align: center;
		line-height: 80upx;
		margin-top: 10upx;
	}
</style>
